﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using SelfService.Model;
using SelfService.Model.Models;
using SelfService.Model.Models.Auto;
using TT;
using WalkingTec.Mvvm.Core;

namespace SelfService.Tasks;

/// <summary>
/// 该任务用于将数据同步到旧系统, 正式上线以后可以移除此任务
/// </summary>
[Display(Name = "支付数据同步")]
public class SysPaySyncTask : BaseTask
{
    private readonly IServiceProvider _provider;
    
    public SysPaySyncTask(WTMContext context, IServiceProvider provider) : base(context)
    {
        _provider = provider;
    }

    public override async Task<bool> Process()
    {
        this.Logger("开始同步支付数据", ActionLogTypesEnum.Normal);
        try
        {
            var dc = Context.DC;
            var list = await dc.Set<SysPay>()
                .Where(e => e.PayStatus == PayStatusEnum.支付成功 && !e.IsSync && e.UseStatus == UseStatusEnum.成功)
                .Include(e => e.Patient)
                .Include(e => e.PayType)
                .ToListAsync();
            var auto = _provider.GetRequiredService<AutoContext>();
            foreach (var element in list)
            {
                var autoPay = new AutoPay();
                autoPay.Name = element.Patient.Name;
                autoPay.PayTime = element.PayTime;
                autoPay.Amount = element.Amount;
                autoPay.IdCardNo = !element.Patient.IdCardNo.IsNullOrWhiteSpace() ? element.Patient.IdCardNo : element.Patient.CardNo;
                autoPay.OrderId = element.OutOrderNo;
                autoPay.TradeNo = element.SerialsNumber;
                autoPay.Status = 30;
                autoPay.HisUserId = element.CreateBy;
                autoPay.CreateTime = element.CreateTime;
                autoPay.UpdateTime = element.UpdateTime ?? element.CreateTime;
                if (element.PayType != null)
                {
                    if (element.PayType.Name == "支付宝") autoPay.PayType = 10;
                    if (element.PayType.Name == "微信") autoPay.PayType = 20;
                }
                if (autoPay.PayType == default)
                {
                    this.Logger($"同步支付数据发生错误, 没有找到对应的支付方式, 详细信息:{JsonConvert.SerializeObject(element)}", ActionLogTypesEnum.Exception);
                    continue;
                }
                await auto.AutoPays.AddAsync(autoPay);
                await auto.SaveChangesAsync();
                element.IsSync = true;
                await dc.SaveChangesAsync();
            }
            return true;
        }
        catch (Exception e)
        {
            this.Logger($"同步支付数据异常{e.Message}, 详细信息:{JsonConvert.SerializeObject(e)}", ActionLogTypesEnum.Exception);
        }
        return false;
    }
}